from django.shortcuts import render
from django.views.decorators.http import *
from django.conf import settings
from .forms import UploadFileForm
from django.http import JsonResponse
import json
import requests as req
from django.core.cache import cache
from django.http import HttpResponseRedirect
from PIL import Image
import hashlib

def upload(request):
    form = UploadFileForm(request.POST, request.FILES)
    # import ipdb; ipdb.set_trace()
    if form.is_valid():
        name = handle_uploaded_file(request.FILES['file'])
    return JsonResponse({'name':name})

def handle_uploaded_file(f):
    tmp = f.name
    suffix = tmp.split('.')[1]
    name = hashlib.md5(tmp.encode('utf8')).hexdigest() + '.' + suffix
    file_name = settings.UPLOAD_DIR + name
    destination = open(file_name, 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
    img = Image.open(file_name)
    img.thumbnail((100,100),Image.ANTIALIAS)
    suffix = f.content_type.split('/')[1]
    img.save(settings.UPLOAD_DIR + name + '100',suffix)
    return name

def exchange(request):
    befrom = 'JPY'
    to = 'cny'
    # to = 'GMD'
    headers = {'apikey':'9a573e65510f673dd6d47d8520606639'}
    url = 'http://apis.baidu.com/apistore/currencyservice/currency'
    data = {'fromCurrency':befrom,'toCurrency':to,'amount':2}
    obj = req.get(url,headers = headers,params = data)
    # import ipdb; ipdb.set_trace()
    # rate = obj.json()['retData']['currency']
    rate = obj.json()['retData']['convertedamount']
    # date = obj.json()['retData']['date']
    # cache.set('rate',rate,60 * 60 * 24)
    cache.set('rate',rate,None)
    return JsonResponse({'rate':rate})

def login_required(func):
    def _login_required(request,**kwargs):
        if not request.session.get('id'):
            return HttpResponseRedirect('/user/login')
        else:
            return func(request,**kwargs)
    return _login_required
